package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.Folder;
import com.entity.User;
import com.util.DBHelp;
import com.util.RowMapper;

public class FolderDao {

	private DBHelp<Folder> db=new DBHelp<Folder>();
	
	public List<Folder> list(){
		String sql = "select tf.id,tf.foldername,tf.createtime,tf.userid,tu.image,tu.username from t_folder AS tf left join t_user AS tu on tf.userid=tu.id";
		return db.executeQueryForList(sql, new FolderRowMapper());
	}
	
	
	private class FolderRowMapper implements RowMapper<Folder> {

		public Folder mapRow(ResultSet rs) throws SQLException {
			
			Folder f=new Folder();
			f.setCreateTime(rs.getString("createtime"));
			f.setFolderName(rs.getString("foldername"));
			f.setId(rs.getString("id"));
			
			
			User u=new User();
			u.setId(rs.getString("userid"));
			u.setUserName(rs.getString("username"));
			
			u.setImage(rs.getString("image"));
			
			f.setUser(u);
			
			f.setUserid(rs.getString("userid"));
			return f;
		}
		
	}

	public void save(Folder folder) {
		String sql = "INSERT INTO t_folder(id,foldername,createtime,userid) values (?,?,?,?)";
		db.executeSQL(sql, folder.getId(),folder.getFolderName(),folder.getCreateTime(),folder.getUserid());
	}

	public Folder find(String folderid) {
		// TODO Auto-generated method stub
		String sql="select tf.id,tf.foldername,tf.createtime,tf.userid,tu.image,tu.username from t_folder AS tf left join t_user AS tu on tu.id=tf.userid where tf.id=?";
		return db.executeQueryForObject(sql, new FolderRowMapper(), folderid);
	}

}
